package com.jy.wms.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.joyi.gate.comm.SessionInfo;
import com.joyi.gate.safety.vo.UserInfo;
import com.jy.wms.common.UUIDUtils;
import com.jy.wms.common.annotions.BaseServiceDescribe;
import com.jy.wms.common.base.*;
import com.jy.wms.dao.WmsLibraryAreaMapper;
import com.jy.wms.pojo.SysHz;
import com.jy.wms.pojo.WmsLibraryArea;
import com.jy.wms.pojo.WmsShipmentOrder;
import com.jy.wms.pojo.WmsWarehouse;
import net.sf.json.JSONObject;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

/**
* @ClassName: WmsLibraryAreaService.java
* @Description: TODO(这里用一句话描述这个类的作用)
* @Author yjs
* @Date Tue Aug 29 15:59:22 GMT+08:00 2017
*/

@Service
public class WmsLibraryAreaService extends BaseService<WmsLibraryAreaMapper,WmsLibraryArea> {
    private static Logger log = LoggerFactory.getLogger(WmsLibraryAreaService.class);
 /**
 * 插入一条记录
 * @param entity 实体对象
 * @return int
 */
 @BaseServiceDescribe(moduleName = "库区管理",btnName = "新增库区")
public void baseInsert( WmsLibraryArea entity) throws Exception {
     Integer i=dao.baseInsert( entity );
     if(i>0){
         throw new SucessException("新增库区信息成功");
     }else{
         throw new ServiceException("新增库区信息失败");
     }
}

    /**
     * 添加前去除重复
     * @param mc
     * @param ckid
     * @param dm
     * @return
     */
    public WmsLibraryArea searchADD(String mc,String ckid,String dm){
        return dao.searchADD(mc, ckid, dm);
    }

    /**
     * 编辑库区查询去重
     *
     * @param mc
     * @param ckid
     * @param dm
     * @param id
     * @return
     */
    public WmsLibraryArea searchEdit(String mc, String ckid, String dm, String id) {
        return dao.searchEdit(mc, ckid, dm, id);
    }

    /**
     * 编辑库区保存
     *
     * @param entity
     * @return
     */
    public void editWmsLibraryArea(WmsLibraryArea entity) throws Exception {
        Integer i = dao.editWmsLibraryArea(entity);
        if (i > 0) {
            throw new SucessException("编辑库区信息成功");
        } else {
            throw new ServiceException("编辑库区信息失败");
        }
    }
/**
* 插入一条记录（匹配有值的字段）
* @param entity 实体对象
* @return int
*/
public Integer baseInsertSelective( WmsLibraryArea entity){
     return dao.baseInsertSelective( entity);
}

/**
* 删除（根据主键ID删除）
* @param id 主键
* @return int
*/
public Integer baseDeleteByPrimaryKey( String id){
     return dao.baseDeleteByPrimaryKey( id);
}

/**
* 删除（根据ID 批量删除）
* @param idList 主键ID列表
* @return int
*/
public Integer baseDeleteBathPrimaryKeys( List<String> idList){
     return dao.baseDeleteBathPrimaryKeys( idList);
}

/**
* 分页查询
* @param entity 实体
* @return Page<WmsLibraryArea>
*/
@BaseServiceDescribe(moduleName = "库区管理",btnName = "分页查询库区")
public Page<WmsLibraryArea> baseSelectPage(WmsLibraryArea entity) throws ServiceException {
    try{
        PageHelper.startPage(entity.getPage(), entity.getRows());
        return (Page<WmsLibraryArea>)dao.baseSelectPage( entity);
    }catch(Exception e){
        throw new ServiceException("查询库区列表失败",e);
    }
}

/**
* 查询（根据主键ID查询）
* @param id 主键ID
* @return WmsLibraryArea
 */
@BaseServiceDescribe(moduleName = "库区管理", btnName = "编辑查询库区信息")
public WmsLibraryArea baseSelectByPrimaryKey(String id) throws Exception {
    return dao.baseSelectByPrimaryKey(id);
}

    /**
     * 查询当前仓库信息
     * @return
     */
public WmsWarehouse addSearchCK(){
    return dao.addSearchCK();
}

    /**
     * 库区导入
     *
     * @param session
     * @param filepath
     * @throws ServiceException
     * @throws SucessException
     * @throws Exception
     */
    @BaseServiceDescribe(moduleName = "库区管理", btnName = "库区导入")
    public void importKQ(HttpSession session, String filepath) throws Exception {
        ImportParams params = new ImportParams();
        params.setNeedSave(false);
        params.setTitleRows(0);
        params.setHeadRows(1);
        params.setDataHanlder(new ShipmentOrderMapImportHanlder());
        UserInfo userinfo = (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
        //仓库id
        String ckid = String.valueOf(userinfo.getUser().getOrgId().get(0));
        JSONObject jb = JSONObject.fromObject(filepath);
        URL url = new URL((String) jb.get("filepath"));
        URLConnection conn = url.openConnection();
        List<Map<String, Object>> result = ExcelImportUtil.importExcel(
                conn.getInputStream(),
                Map.class, params);
        log.info("库区导入result:" + result);
        for (int i = 0; i < result.size(); i++) {
            result.get(i).put("num", i + 2);
        }
        //表格内去重
        removeExcel(result);
        //数据库去重
        removeDataDuplicate(result, ckid);
        WmsLibraryArea wmsLibraryArea = null;
        for (Map<String, Object> map : result) {
            wmsLibraryArea = new WmsLibraryArea();
            wmsLibraryArea.setId(UUIDUtils.uuid());
            //名称
            wmsLibraryArea.setMc(map.get("kqmc").toString());
            //代码
            wmsLibraryArea.setDm(map.get("kqdm").toString());
            //备注
            wmsLibraryArea.setBz(map.get("bz").toString());
            //是否有效
            wmsLibraryArea.setSfyx("1");
            //仓库id
            wmsLibraryArea.setCkid(ckid);
            //添加库区
            Integer i = dao.baseInsert(wmsLibraryArea);
            if (i > 0) {
                throw new SucessException("新增库区信息成功");
            } else {
                throw new ServiceException("新增库区信息失败");
            }
        }

    }

    /**
     * 报表内去重
     *
     * @param list
     * @throws Exception
     */
    public void removeExcel(List<Map<String, Object>> list) throws Exception {
        //报表内库区名称以及库区代码都不可以重复
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < list.size() - 1; i++) {
            for (int j = i + 1; j < list.size(); j++) {
                if (list.get(j).get("kqmc").equals(list.get(i).get("kqmc"))) {
                    sb.append("第" + list.get(j).get("num") + "行,库区名称：" + list.get(j).get("kqmc") + ",");
                    list.remove(j);
                    j--;
                } else if (list.get(j).get("kqdm").equals(list.get(i).get("kqdm"))) {
                    sb.append("第" + list.get(j).get("num") + "行,库区代码:" + list.get(j).get("kqdm") + ",");
                    list.remove(j);
                    j--;
                }
            }
        }
        if (sb != null && !"".equals(sb) && sb.length() > 0) {
            throw new ServiceException("表格中" + sb + "内容重复，导入失败");
        }
    }

    /**
     * 数据库去重
     *
     * @param list
     * @param ckid
     * @throws Exception
     */
    public void removeDataDuplicate(List<Map<String, Object>> list, String ckid) throws Exception {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < list.size(); i++) {
            //查询库区名称是否存在
            WmsLibraryArea wmsLibraryAreaMc = dao.searchADD(list.get(i).get("kqmc").toString(), ckid, "");
            //查询库区代码是否存在
            WmsLibraryArea wmsLibraryAreaDm = dao.searchADD("", ckid, list.get(i).get("kqdm").toString());
            if (wmsLibraryAreaMc != null) {
                sb.append("第" + list.get(i).get("num") + "行,库区名称:" + list.get(i).get("kqmc") + ",");
            } else if (wmsLibraryAreaDm != null) {
                sb.append("第" + list.get(i).get("num") + "行,库区代码:" + list.get(i).get("kqdm") + ",");
            }
        }
        if (sb != null && !"".equals(sb) && sb.length() > 0) {
            throw new ServiceException(sb + "数据库包含重复数据,导入失败");
        }
    }
}
